package com.speedcar.base.i18n;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

public class ScI18nUtils {

    private static final Logger logger = LoggerFactory.getLogger(ScI18nUtils.class);

    private static MessageSource messageSource;

    // 通过setter注入避免静态字段问题
    public static void setMessageSource(MessageSource messageSource) {
        ScI18nUtils.messageSource = messageSource;
    }

    // 自动从请求头获取语言
    public static String get(String code) {
        Locale locale = getLocaleFromRequest();
        return messageSource.getMessage(code, null, locale);
    }

    // 手动指定语言
    public static String get(String code, String language) {
        Locale locale = parseLocale(language);
        return messageSource.getMessage(code, null, locale);
    }

    // 基础方法：带参数和语言
    public static String get(String code, Object[] args) {
        try {
            Locale locale = getLocaleFromRequest();
            return messageSource.getMessage(code, args, locale);
        } catch (Exception e) {
            logger.warn("I18n message not found for code: {}", code);
            return code; // 返回代码作为回退
        }
    }


    // 基础方法：带参数和语言
    public static String get(String code, Object[] args, String language) {
        try {
            Locale locale = parseLocale(language);
            return messageSource.getMessage(code, args, locale);
        } catch (Exception e) {
            logger.warn("I18n message not found for code: {}", code);
            return code; // 返回代码作为回退
        }
    }

    // 手动指定语言的带参数版本
    public static String getWithLanguage(String code, String language, Object... args) {
        return get(code, args, language);
    }

    // 从请求头解析语言
    private static Locale getLocaleFromRequest() {
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String langHeader = request.getHeader("Accept-Language");
            return parseLocale(langHeader);
        }
        return Locale.SIMPLIFIED_CHINESE;
    }

    // JDK 8兼容的语言解析
    private static Locale parseLocale(String language) {
        if (language == null || language.isEmpty()) {
            return Locale.SIMPLIFIED_CHINESE;
        }

        String lowerLang = language.toLowerCase();
        if (lowerLang.contains("en")) {
            return Locale.ENGLISH;
        } else if (lowerLang.contains("ru")) {
            return new Locale("ru", "RU");
        } else {
            return Locale.SIMPLIFIED_CHINESE;
        }
    }
}